﻿using Iodll;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfZMotion_DHAgeingOven.Core.IO;

namespace FinalTestMachine.Core.Core.IO
{
    public class IOManger
    {
        public static readonly IOManger Instance = new IOManger();

        public static readonly Iodll.IoControlContainer IoMsg;

        static IOManger()
        {
            InputDict = new IODictionary<string, Iodll.IoInHelper>();
            OutputDict = new IODictionary<string, IoOutHepler>();
            IOModuleDict = new Dictionary<string, IoControl>();
            IoMsg = new Iodll.IoControlContainer();
            InitIOModule();
            InitInput();
            InitOutput();
        }

        public IOManger CreateInstance()
        {
            return Instance;
        }

        const int IOMODULE_SPLIT_COUNT = 5;
        const int INPUT_SPLIT_COUNT = 3;
        const int OUTPUT_SPLIT_COUNT = 5;

        static string _ioModuleFilePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "AviewConfigs", "Axis", "IOModuleInfo.csv");
        static string _inputFilePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "AviewConfigs", "Axis", "Input.csv");
        static string _outputFilePath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "AviewConfigs", "Axis", "Output.csv");

        public static IODictionary<string, Iodll.IoInHelper> InputDict { get; private set; }
        public static IODictionary<string, IoOutHepler> OutputDict { get; private set; }
        public static Dictionary<string, IoControl> IOModuleDict { get; private set; }
        static void InitIOModule()
        {
            if (!System.IO.File.Exists(_ioModuleFilePath))
            {
                System.Windows.MessageBox.Show("IO模块配置文件不存在");
                return;
            }
            try
            {
                int line = 1;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(_ioModuleFilePath, System.Text.Encoding.GetEncoding("GB2312")))
                {
                    if (sr.Peek() > 0)
                        sr.ReadLine();  //第一行扔掉
                    while (sr.Peek() > 0)
                    {
                        ++line;
                        string content = sr.ReadLine();
                        if (content.Contains(','))
                        {
                            string[] itemArray = content.Split(',');
                            if (itemArray.Length != IOMODULE_SPLIT_COUNT)
                            {
                                System.Windows.MessageBox.Show("IO模块配置文件格式不正确，行号:" + line.ToString());
                                return;
                            }
                            string name = itemArray[0];
                            string ip = itemArray[1];
                            byte devNo = byte.Parse(itemArray[2]);
                            int inNums = int.Parse(itemArray[3]);
                            int outNums = int.Parse(itemArray[4]);

                            IoControl ioCard;
                            if (IOModuleDict.ContainsKey(name))
                            {
                                System.Windows.MessageBox.Show("IO卡名称已经存在，" + "行号:" + line.ToString());
                                return;
                            }
                            else
                            {
                                ioCard = new ZMotionHelper.IO.EcatIoHelper(ip, name, devNo, inNums, outNums, 128, IoMsg);
                                IOModuleDict.Add(name, ioCard);
                            }
                        }
                        else
                        {
                            System.Windows.MessageBox.Show("IO模块配置文件格式不正确，缺少逗号分隔符");
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("IO模块配置异常:" + ex.Message);
            }


        }
        static void InitInput()
        {
            if (!System.IO.File.Exists(_inputFilePath))
            {
                System.Windows.MessageBox.Show("IO输入点位配置文件不存在");
                return;
            }
            try
            {
                int line = 1;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(_inputFilePath, System.Text.Encoding.GetEncoding("GB2312")))
                {
                    if (sr.Peek() > 0)
                        sr.ReadLine();  //第一行扔掉
                    while (sr.Peek() > 0)
                    {
                        ++line;
                        string content = sr.ReadLine();
                        if (content.Contains(','))
                        {
                            string[] itemArray = content.Split(',');
                            if (itemArray.Length != INPUT_SPLIT_COUNT)
                            {
                                System.Windows.MessageBox.Show("配置IO输入点位失败,IO配置文件格式不正确，行号:" + line.ToString());
                                return;
                            }
                            string name = itemArray[0];
                            string moduleName = itemArray[1];
                            byte[] indexArray;
                            string strIndex = itemArray[2];
                            if (strIndex.Contains('_'))
                            {
                                string[] strIndexArray = strIndex.Split('_');
                                List<byte> list = new List<byte>();
                                for (int i = 0; i < strIndexArray.Length; i++)
                                {
                                    list.Add(byte.Parse(strIndexArray[i]));
                                }
                                indexArray = list.ToArray();
                            }
                            else
                            {
                                indexArray = new byte[] { byte.Parse(strIndex) };
                            }

                            IoControl ioControl;
                            if (IOModuleDict.ContainsKey(moduleName))
                            {
                                ioControl = IOModuleDict[moduleName];
                            }
                            else
                            {
                                System.Windows.MessageBox.Show($"配置IO输入点位失败,行号:{line},IO模块名称不存在:" + moduleName);
                                return;
                            }
                            Iodll.IoInHelper input = new Iodll.IoInHelper(ioControl, name, indexArray);
                            InputDict.Add(name, input);
                        }
                        else
                        {
                            System.Windows.MessageBox.Show($"配置IO输入点位失败,IO配置文件格式不正确，行号:{line},缺少逗号分隔符");
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("IO输入点位配置异常:" + ex.Message);
            }

        }
        static void InitOutput()
        {
            if (!System.IO.File.Exists(_outputFilePath))
            {
                System.Windows.MessageBox.Show("IO输出点位配置文件不存在");
                return;
            }
            try
            {
                int line = 1;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(_outputFilePath, System.Text.Encoding.GetEncoding("GB2312")))
                {
                    if (sr.Peek() > 0)
                        sr.ReadLine();  //第一行扔掉
                    while (sr.Peek() > 0)
                    {
                        ++line;
                        string content = sr.ReadLine();
                        if (content.Contains(','))
                        {
                            string[] itemArray = content.Split(',');
                            if (itemArray.Length != OUTPUT_SPLIT_COUNT)
                            {
                                System.Windows.MessageBox.Show("IO输出点位配置文件格式不正确，行号:" + line.ToString());
                                return;
                            }
                            string name = itemArray[0];
                            string moduleName = itemArray[1];
                            byte[] indexArray;
                            string strIndex = itemArray[2];
                            if (strIndex.Contains('_'))
                            {
                                string[] strIndexArray = strIndex.Split('_');
                                List<byte> list = new List<byte>();
                                for (int i = 0; i < strIndexArray.Length; i++)
                                {
                                    list.Add(byte.Parse(strIndexArray[i]));
                                }
                                indexArray = list.ToArray();
                            }
                            else
                            {
                                indexArray = new byte[] { byte.Parse(strIndex) };
                            }
                            bool isAddButton = false;
                            if (itemArray[3].ToUpper() == "TRUE")
                            {
                                isAddButton = true;
                            }
                            string buttonName = itemArray[4];
                            IoControl ioControl;
                            if (IOModuleDict.ContainsKey(moduleName))
                            {
                                ioControl = IOModuleDict[moduleName];
                            }
                            else
                            {
                                System.Windows.MessageBox.Show($"配置IO输出点位失败,行号:{line},IO模块名称不存在:" + moduleName);
                                return;
                            }

                            IoOutHepler output = new IoOutHepler(ioControl, name, buttonName, isAddButton, indexArray);
                            OutputDict.Add(name, output);
                        }
                        else
                        {
                            System.Windows.MessageBox.Show("IO输出点位配置文件格式不正确，缺少逗号分隔符");
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("IO输出点位配置异常:" + ex.Message);
            }


        }




    }
}
